<template>
  <div class="wrap-item">
    <!-- 搜索-->
    <el-form ref="formSearch" :model="formSearch" size="small" inline>
      <el-form-item>
        <el-input
          v-model.trim="formSearch.param.userName"
          placeholder="请输入姓名"
          maxlength="20"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model.trim="formSearch.param.phone"
          placeholder="请输入联系电话"
          maxlength="11"
          clearable
        ></el-input
      ></el-form-item>
      <el-form-item>
        <el-select
          clearable
          v-model="formSearch.param.userStatus"
          placeholder="请选择状态"
        >
          <el-option label="启用" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <span class="wrap-btn wrap-primary" @click="search">查询</span>
        <span
          class="wrap-btn wrap-success"
          v-if="$checkPermission(101)"
          @click="add"
          >添加用户</span
        >
      </el-form-item>
    </el-form>
    <!-- 数据列表 -->
    <div class="wrap-item-roll">
      <el-table
        :data="tableData"
        :header-cell-style="{ background: '#F6F7F9' }"
      >
        <el-table-column
          type="index"
          width="50"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column prop="userName" label="姓名"></el-table-column>
        <el-table-column label="用户分组" width="300px">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.groups" :key="index">
              {{
                item.groupName +
                (scope.row.groups.length == index + 1 ? '' : ',')
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column label="所在组织机构">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.units" :key="index">
              {{
                item.orgName + (scope.row.units.length == index + 1 ? '' : ',')
              }}
            </span>
          </template></el-table-column
        >
        <el-table-column prop="addName" label="创建人"></el-table-column>
        <el-table-column
          prop="addTime"
          label="创建时间"
          width="160px"
        ></el-table-column>
        <el-table-column label="状态" width="80px" align="center">
          <template slot-scope="scope">
            <el-link
              type="success"
              :underline="false"
              v-if="scope.row.userStatus == 0"
              >启用</el-link
            >
            <el-link
              type="danger"
              :underline="false"
              v-if="scope.row.userStatus == 1"
              >停用</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="操作"
          width="80px"
          align="center"
        >
          <template slot-scope="scope">
            <el-dropdown @command="(command) => handle(command, scope.row)">
              <span class="el-dropdown-link">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="view" v-if="$checkPermission(104)"
                  >查看</el-dropdown-item
                >
                <el-dropdown-item command="edit" v-if="$checkPermission(102)"
                  >编辑</el-dropdown-item
                >
                <el-dropdown-item
                  command="changeStatus"
                  v-if="scope.row.userStatus == 1 && $checkPermission(105)"
                  >启用</el-dropdown-item
                >
                <el-dropdown-item
                  command="changeStatus"
                  v-if="scope.row.userStatus == 0 && $checkPermission(106)"
                  >停用</el-dropdown-item
                >
                <el-dropdown-item command="remove" v-if="$checkPermission(103)"
                  >删除</el-dropdown-item
                >
                <el-dropdown-item command="reset" v-if="$checkPermission(107)"
                  >重置密码</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <web-page
      :page="formSearch.pageNum"
      :size="formSearch.pageSize"
      :total="total"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
    ></web-page>
    <!-- 对话框 -->
    <el-drawer :title="title" :wrapperClosable="false" :visible.sync="visible">
      <el-form label-width="80px" :model="form" size="medium">
        <el-form-item label="姓名" required>
          <el-input
            v-model.trim="form.userName"
            clearable
            maxlength="20"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" required>
          <el-input
            v-model.trim="form.phone"
            clearable
            maxlength="11"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户分组" required>
          <el-select
            clearable
            multiple
            v-model="form.groupId"
            value-key="id"
            placeholder="请选择用户分组"
            style="width: 100%"
          >
            <el-option
              v-for="item in groupData"
              :key="item.id"
              :label="item.groupName"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织机构" required>
          <el-tree
            ref="tree"
            node-key="id"
            :accordion="true"
            :data="orgData"
            show-checkbox
            default-expand-all
            :check-strictly="true"
            :props="defaultProps"
            style="margin-top: 5px !important"
          ></el-tree>
        </el-form-item>
        <el-form-item label="角色" required>
          <el-select
            clearable
            multiple
            filterable
            v-model="form.roleIds"
            value-key="id"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleData"
              :key="item.id"
              :label="item.roleName"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号">
          <el-input
            v-model.trim="form.workNum"
            clearable
            maxlength="10"
            placeholder="请输入工号"
          ></el-input>
        </el-form-item>
        <el-form-item label="职位">
          <el-input
            v-model.trim="form.workPost"
            clearable
            maxlength="20"
            placeholder="请输入职位"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model.trim="form.email"
            clearable
            maxlength="50"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item style="text-align: end">
          <span class="wrap-btn wrap-success" @click="save">确定</span>
          <span class="wrap-btn wrap-default" @click="visible = false"
            >取消</span
          >
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 查看 -->
    <el-dialog title="查看" :visible.sync="isLook" width="930px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">
          {{ lockData.userName }}
        </el-descriptions-item>
        <el-descriptions-item label="用户分组">
          <i v-for="(item, index) in lockData.groupId" :key="index">
            {{
              item.groupName + (lockData.groupId.length == index + 1 ? '' : ',')
            }}
          </i>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ lockData.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="所在组织机构">
          <i v-for="(item, index) in lockData.orgIds" :key="index">
            {{
              item.orgName + (lockData.orgIds.length == index + 1 ? '' : ',')
            }}
          </i>
        </el-descriptions-item>
        <el-descriptions-item label="角色" :span="2">
          <i v-for="(item, index) in lockData.roleIds" :key="index">
            {{
              item.roleName + (lockData.roleIds.length == index + 1 ? '' : ',')
            }}
          </i>
        </el-descriptions-item>
        <el-descriptions-item label="工号">
          {{ lockData.workNum }}
        </el-descriptions-item>
        <el-descriptions-item label="职位">
          {{ lockData.workPost }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱" :span="2">
          {{ lockData.email }}
        </el-descriptions-item>
        <el-descriptions-item
          label="子账号"
          :span="2"
          v-if="lockData.child?.length"
        >
          <el-table :data="lockData.child">
            <el-table-column prop="accountName" label="账号"> </el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>
            <el-table-column prop="size" label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.accountType == 0">外部用户账号</span>
                <span v-if="scope.row.accountType == 1">内部管理员账号</span>
              </template>
            </el-table-column>
            <el-table-column prop="size" label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status == 0">启用</span>
                <span v-if="scope.row.status == 1">停用</span>
              </template>
            </el-table-column>
            <el-table-column prop="addTime" label="创建时间"></el-table-column>
          </el-table>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { isPhone, isEmail } from '@u/validate'
export default {
  data() {
    return {
      groupData: [],
      orgData: [],
      roleData: [],
      defaultProps: {
        children: 'child',
        label: 'orgName',
      },
      formSearch: {
        pageNum: 1,
        pageSize: 10,
        param: {},
      },
      total: null,
      tableData: [],
      visible: false,
      title: '添加用户',
      form: {},
      isLook: false,
      lockData: { child: [] },
    }
  },
  created() {
    this.groupList()
    this.orgList()
    this.roleList()
    this.itemList()
  },
  methods: {
    itemList() {
      // 获取列表
      this.$axios.post('/admin/user/page', this.formSearch).then((data) => {
        this.tableData = []
        if (data.code == 200) {
          this.tableData = data.data.list
          this.total = data.data.total
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    sizeChange(val) {
      //每页条数
      this.formSearch.pageSize = val
      this.itemList()
    },
    currentChange(val) {
      //分页
      this.formSearch.pageNum = val
      this.itemList()
    },
    search() {
      //搜索
      this.formSearch.pageNum = 1
      this.itemList()
    },
    add() {
      //添加
      this.title = '添加用户'
      this.form = { groupId: [], roleIds: [], orgIds: [] }
      this.visible = true
      this.$nextTick(function () {
        this.$refs.tree.setCheckedKeys([])
      })
    },
    handle(command, row) {
      //操作
      if (!command) {
        this.$message.error('菜单选项缺少command属性')
        return
      }
      switch (command) {
        case 'view':
          //查看
          this.$axios.get('/admin/user/find?id=' + row.id).then((data) => {
            this.lockData = { child: [] }
            if (data.code == 200) {
              this.lockData = data.data
              this.isLook = true
            } else {
              this.$message.error(data.msg)
            }
          })
          break
        case 'edit':
          this.title = '编辑用户'
          this.$axios.get('/admin/user/find?id=' + row.id).then((data) => {
            this.form = { groupId: [], roleIds: [], orgIds: [] }
            if (data.code == 200) {
              this.form = data.data
              const orgId = []
              data.data.orgIds.forEach((element) => {
                orgId.push(element.id)
              })
              this.$nextTick(() => {
                this.$refs.tree.setCheckedKeys(orgId)
              })
              this.role = []
              data.data.roleIds.forEach((element) => {
                this.role.push({
                  value: element.id,
                  label: element.roleName,
                })
              })
              this.visible = true
            } else {
              this.$message.error(data.msg)
            }
          })
          break
        case 'changeStatus':
          //启用停用
          const status = row.userStatus == 0 ? 1 : 0
          this.$axios
            .get('/admin/user/start?id=' + row.id + '&status=' + status)
            .then((data) => {
              if (data.code == 200) {
                this.itemList()
                this.$message.success('操作成功！')
              } else {
                this.$message.error(data.msg)
              }
            })
          break
        case 'remove':
          //删除
          this.$confirm('您确定要删除该条数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.$axios.get('/admin/user/del?id=' + row.id).then((data) => {
                if (data.code == 200) {
                  this.itemList()
                  this.$message.success('操作成功！')
                } else {
                  this.$message.error(data.msg)
                }
              })
            })
            .catch(() => {})
          break
        case 'reset':
          //重置密码
          this.$confirm('您确认重置密码吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.$axios
                .get('/admin/user/restPass?id=' + row.id)
                .then((data) => {
                  if (data.code == 200) {
                    this.$confirm(
                      '密码重置成功，新密码为：' + data.data,
                      '提示',
                      {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                      }
                    )
                      .then(() => {})
                      .catch(() => {})
                  } else {
                    this.$message.error(data.msg)
                  }
                })
            })
            .catch(() => {})
          break
      }
    },
    save() {
      //保存
      if (!this.form.userName) {
        this.$message.error('请输入姓名')
        return
      }
      if (!isPhone(this.form.phone)) {
        this.$message.error('请输入正确的手机号')
        return
      }
      if (this.form.groupId.length == 0) {
        this.$message.error('请选择用户分组')
        return
      }
      const dept = this.$refs.tree.getCheckedNodes()
      if (dept.length == 0) {
        this.$message.error('请选择组织机构')
        return
      }
      this.form.orgIds = []
      dept.forEach((element) => {
        this.form.orgIds.push({
          id: element.id,
          orgName: element.orgName,
        })
      })
      if (this.form.roleIds.length == 0) {
        this.$message.error('请选择角色')
        return
      }
      if (this.form.email && !isEmail(this.form.email)) {
        this.$message.error('请输入正确的邮箱')
        return
      }
      this.$axios.post('/admin/user/edit', this.form).then((data) => {
        if (data.code == 200) {
          this.visible = false
          if (data.data) {
            this.$confirm('当前用户密码为：' + data.data, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {})
              .catch(() => {})
          } else {
            this.$message.success('操作成功！')
          }
          this.itemList()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    groupList() {
      // 获取用户分组
      this.$axios.get('/admin/group/list').then((data) => {
        this.groupData = []
        if (data.code == 200) {
          data.data.forEach((element) => {
            this.groupData.push({
              id: element.id,
              groupName: element.groupName,
            })
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    orgList() {
      // 获取机构
      this.$axios.get('/admin/org/listTree?parentNo=0').then((data) => {
        this.orgData = []
        if (data.code == 200) {
          this.orgData = data.data
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    roleList() {
      // 获取角色
      this.$axios.get('/admin/role/listRole').then((data) => {
        this.roleData = []
        if (data.code == 200) {
          data.data.forEach((element) => {
            this.roleData.push({
              id: element.id,
              roleName: element.roleName,
            })
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
  },
}
</script>
